import pandas as pd
import tushare as ts
from chinese_calendar import is_holiday
import time
import datetime
import numpy as np

ts.set_token("6667cd4a2326f2f937062a0f4fb59aea5c56d13b1f6f26225f115fe9")
pro = ts.pro_api()

def n_days_before(st_day,n):
    """
    st_day:开始日期
    :type st_day: datetime.date | datetime.datetime
    """
    while(n>0):
        if not is_holiday(st_day):
            n=n-1
        st_day=st_day-datetime.timedelta(1)
    return st_day

days=100
end_date_str=time.strftime("%Y%m%d") 
end_datetime = datetime.datetime.strptime(end_date_str, '%Y%m%d') 
start_datetime=n_days_before(end_datetime,days) 
start_date_str=start_datetime.strftime("%Y%m%d") 

df=pro.daily(ts_code="000799.SZ", start_date=start_date_str, end_date=end_date_str)
OPEN=df["open"]

def fun2ploy(x,n):  #得到范德蒙德（Vandermonde）行列式,#https://zhuanlan.zhihu.com/p/38128785/
    '''
    数据转化为[x^0,x^1,x^2,...x^n]
    首列变1
    '''
    lens = len(x)
    X = np.ones([1,lens])
    for i in range(1,n):
        X = np.vstack((X,np.power(x,i)))#按行堆叠
    #print('Vandermonde行列式:',X)
    return X  

def leastseq_byploy(x,y,ploy_dim):  #https://blog.csdn.net/dz4543/article/details/85224391
    '''
    最小二乘求解
  '''
    X = fun2ploy(x,ploy_dim)
    #直接求解
    Xt = X.transpose();#转置变成列向量 X=[[x^0][x^1][x^2][x^3]]
    XXt=X.dot(Xt);#矩阵乘,X*X^T
    XXtInv = np.linalg.inv(XXt)#求逆 (X*X^T)^-1
    XXtInvX = XXtInv.dot(X) #(X*X^T)^-1*X
    #获得系数列向量
    coef = XXtInvX.dot(y.T)
    y_est = Xt.dot(coef)
    return y_est,coef


def tst(x,n):  #得到范德蒙德（Vandermonde）行列式,#https://zhuanlan.zhihu.com/p/38128785/
    '''
    数据转化为[x^0,x^1,x^2,...x^n]
    首列变1
    '''
    lens = len(x)
    
    return lens *n

print(pd.Series(OPEN).rolling(7).agg(tst,2))